﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using System.IO;

namespace CarBloke
{
    public partial class App : Application
    {
        private const int TRIAL_DURATION_DAYS = 20;

        private const string TRIAL_START_BREADCRUMB_FILE = "trial";

        private const string VEHICLE_STORAGE_FILE_PREFIX = "vehicle.";

        private const string VEHICLE_STATS_STORAGE_FILE_PREFIX = "stats.";

        private const string VEHICLE_LOG_STORAGE_FILE_PREFIX = "logbook.";

        private static Dictionary<Guid, List<LogEntry>> cachedLogEntries = new Dictionary<Guid, List<LogEntry>>();

        // Easy access to the root frame
        public PhoneApplicationFrame RootFrame { get; private set; }

        // Constructor
        public App()
        {
            // Global handler for uncaught exceptions. 
            // Note that exceptions thrown by ApplicationBarItem.Click will not get caught here.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();
        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion

        #region application registry

        internal static int GetRemainingTrialDays()
        {
            int daysLeft = 0;
            XmlSerializer serializer = new XmlSerializer(typeof(DateTime));

            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String trailStartBreadcrumbFile = TRIAL_START_BREADCRUMB_FILE;
                if (isolatedStorage.FileExists(trailStartBreadcrumbFile))
                {
                    using (IsolatedStorageFileStream reader = new IsolatedStorageFileStream(trailStartBreadcrumbFile, FileMode.Open, isolatedStorage))
                    {
                        DateTime expireTime = (DateTime)serializer.Deserialize(reader);
                        DateDifference difference = new DateDifference(DateTime.Now, expireTime);
                        daysLeft = difference.Days;

                        if (expireTime < DateTime.Now)
                            daysLeft *= -1;
                    }
                }
                else
                {
                    using (IsolatedStorageFileStream writer = new IsolatedStorageFileStream(trailStartBreadcrumbFile, FileMode.Create, isolatedStorage))
                    {
                        daysLeft = TRIAL_DURATION_DAYS;
                        DateTime expireTime = DateTime.Now.AddDays(daysLeft);
                        serializer.Serialize(writer, expireTime);
                    }
                }
            }

            return daysLeft;
        }

        internal static void SaveVehicle(Vehicle vehicle)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));

            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String vehicleFile = getVehicleFile(vehicle.ID);
                using (IsolatedStorageFileStream writer = new IsolatedStorageFileStream(vehicleFile, FileMode.Create, isolatedStorage))
                {
                    serializer.Serialize(writer, vehicle);
                }
            }
        }

        internal static Vehicle LoadVehicle(Guid id)
        {
            Vehicle loadedVehicle = null;
            XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));            

            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String vehicleFile = getVehicleFile(id);
                if (isolatedStorage.FileExists(vehicleFile))
                {
                    using (IsolatedStorageFileStream reader = new IsolatedStorageFileStream(vehicleFile, FileMode.Open, isolatedStorage))
                    {
                        loadedVehicle = (Vehicle)serializer.Deserialize(reader);
                    }
                }
            }

            return loadedVehicle;
        }

        internal static List<Vehicle> LoadVehicles()
        {
            List<Vehicle> loadedVehicles = new List<Vehicle>();
            XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));

            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                foreach (String vehicleFile in getVehicleFiles())
                {
                    using (IsolatedStorageFileStream reader = new IsolatedStorageFileStream(vehicleFile, FileMode.Open, isolatedStorage))
                    {
                        Vehicle loadedVehicle = (Vehicle)serializer.Deserialize(reader);
                        loadedVehicles.Add(loadedVehicle);
                    }
                }
            }

            return loadedVehicles;
        }

        internal static void DeleteVehicle(Guid id)
        {
            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String vehicleFile = getVehicleFile(id);
                isolatedStorage.DeleteFile(vehicleFile);
            }
        }

        internal static void SaveLogEntry(LogEntry logEntry)
        {
            //NOTE: No locks are present currently becuase logs are only accessed from the UI thread.
            //      If this changes, locks are absolutely necessary.

            List<LogEntry> logs = LoadLogEntries(logEntry.VehicleID);

            //The list in cachedLogEntries is backing this collection
            LogEntry oldLogEntry = logs.FirstOrDefault(log => log.ID == logEntry.ID);
            if (oldLogEntry != null)
            {
                int index = logs.IndexOf(oldLogEntry);
                logs[index] = logEntry;
            }
            else
            {
                logs.Add(logEntry);
            }

            //Update the log file on the disk
            String logBookFile = getLogFile(logEntry.VehicleID);
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<LogEntry>));
                using (IsolatedStorageFileStream writer = new IsolatedStorageFileStream(logBookFile, FileMode.Create, file))
                {
                    serializer.Serialize(writer, logs);
                }
            }

            //Save an updated stat set using the latest logs
            saveVehicleStats(logEntry.VehicleID);
        }

        internal static void DeleteLogEntry(LogEntry logEntry)
        {
            //NOTE: No locks are present currently becuase logs are only accessed from the UI thread.
            //      If this changes, locks are absolutely necessary.

            List<LogEntry> logs = LoadLogEntries(logEntry.VehicleID);

            //The list in cachedLogEntries is backing this collection
            LogEntry oldLogEntry = logs.FirstOrDefault(log => log.ID == logEntry.ID);
            if (oldLogEntry != null)
            {
                int index = logs.IndexOf(oldLogEntry);
                logs.RemoveAt(index);
            }

            //Update the log file on disk
            String logBookFile = getLogFile(logEntry.VehicleID);
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<LogEntry>));
                using (IsolatedStorageFileStream writer = new IsolatedStorageFileStream(logBookFile, FileMode.Create, file))
                {
                    serializer.Serialize(writer, logs);
                }
            }

            //Save an updated stat set using the latest logs
            saveVehicleStats(logEntry.VehicleID);
        }

        internal static LogEntry LoadPriorLogEntry(Guid vehicleID, Guid logID, LogEntry.LogTypes logType)
        {
            LogEntry priorLog = null;

            var allLogs = LoadLogEntries(vehicleID).OrderByDescending(log => log.LogTime).ToList();
            var foundLog = allLogs.Where(log => log.ID == logID).FirstOrDefault();

            if (foundLog != null)
            {
                int logIndexStart = allLogs.IndexOf(foundLog) + 1;
                while (logIndexStart < allLogs.Count)
                {
                    LogEntry candidateLog = allLogs.ElementAt(logIndexStart++);
                    if (candidateLog.LogType == logType)
                    {
                        priorLog = candidateLog;
                        break;
                    }
                }
            }

            return priorLog;
        }

        internal static LogEntry LoadLogEntry(Guid vehicleID, Guid logID)
        {
            return LoadLogEntries(vehicleID).FirstOrDefault((log) => log.ID == logID);
        }

        internal static List<LogEntry> LoadLogEntries(Guid vehicleID)
        {
            //NOTE: No locks are present currently becuase logs are only accessed from the UI thread.
            //      If this changes, locks are absolutely necessary.

            //Try to hit the cache
            if (cachedLogEntries.ContainsKey(vehicleID))
                return cachedLogEntries[vehicleID];

            //Cache failed, load from disk 
            List<LogEntry> logEntries = new List<LogEntry>();
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String logBookFile = getLogFile(vehicleID);

                if (file.FileExists(logBookFile))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<LogEntry>));
                    using (IsolatedStorageFileStream reader = new IsolatedStorageFileStream(logBookFile, FileMode.Open, file))
                    {
                        logEntries = (List<LogEntry>)serializer.Deserialize(reader);
                    }
                }
            }

            //Cache the loaded log entry set for quicker access in the future
            cachedLogEntries.Add(vehicleID, logEntries);

            return logEntries;
        }

        internal static VehicleStats LoadVehicleStats(Guid vehicleID)
        {
            VehicleStats stats = null;

            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String statsFile = getStatsFile(vehicleID);

                if (isolatedStorage.FileExists(statsFile))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(VehicleStats));
                    using (IsolatedStorageFileStream reader = new IsolatedStorageFileStream(statsFile, FileMode.Open, isolatedStorage))
                    {
                        stats = (VehicleStats)serializer.Deserialize(reader);
                    }
                }
            }

            return stats;
        }

        private static void saveVehicleStats(Guid vehicleID)
        {
            VehicleStats stats = VehicleMath.CalculateVehicleStats(vehicleID);
            String statsFile = getStatsFile(vehicleID);

            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(VehicleStats));
                using (IsolatedStorageFileStream writer = new IsolatedStorageFileStream(statsFile, FileMode.Create, file))
                {
                    serializer.Serialize(writer, stats);
                }
            }

        }

        private static String getVehicleFile(Guid vehicleID)
        {
            return VEHICLE_STORAGE_FILE_PREFIX + vehicleID.ToString();
        }

        private static String getStatsFile(Guid vehicleID)
        {
            return VEHICLE_STATS_STORAGE_FILE_PREFIX + vehicleID.ToString();
        }

        private static List<String> getVehicleFiles()
        {
            List<String> vehicleFiles = new List<String>();

            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String[] files = isolatedStorage.GetFileNames();

                foreach (String file in files)
                {
                    if (file.StartsWith(VEHICLE_STORAGE_FILE_PREFIX))
                    {
                        vehicleFiles.Add(file);
                    }
                }
            }

            return vehicleFiles;
        }

        private static String getLogFile(Guid vehicleID)
        {
            return VEHICLE_LOG_STORAGE_FILE_PREFIX + vehicleID.ToString();
        }

        #endregion
    }
}
